const BaseController = require('../core/BaseController');
const fs = require('mz/fs');
const path = require('path');
const { HttpStatus } = require('../util/enum');


module.exports = class extends BaseController {
  constructor(props) {
    super(props);
    this.tableName = 'img';
  }

  async upload() {
    const { ctx, app } = this;
    const file = ctx.request.files[0];
    if (!(file && file.filepath && file.mime.indexOf('image') > -1)) {
      ctx.status = HttpStatus.BAD_REQUEST;
      return ctx.fail({
        code: '参数错误',
        field: 'file',
        message: '请传正常的图片格式'
      });
    }
    const ext = file.mime.split('/')[1];
    const create_time = Date.now();
    const newFileName = create_time + '.' + ext;
    const newFilePath = path.join('public/upload/', newFileName);
    const realPath = path.join(ctx.app.baseDir, 'app/', newFilePath);
    let rs = {};
    if (!await fs.rename(file.filepath, realPath)) {
      rs = await app.mysql.insert(this.tableName, { path: newFilePath, create_time });
    }
    return rs.insertId > 0 ? ctx.success({ id: rs.insertId, path: newFilePath }) : ctx.fail('上传图片失败');
  }
};
